﻿using System;
using System.ComponentModel;
using System.IO;
using System.Windows;

using Gamey;

namespace Gamey.UI
{
    /// <summary>
    /// Interaction logic for SettingsWindow.xaml
    /// </summary>
    public partial class SettingsWindow : Elysium.Controls.Window
    {
        public SettingsWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.propertyGrid.SelectedObject = Env.Settings;

            if (Env.Settings.IsEmpty && !TryToFindSettingsAutomatically())
            {
                MessageBox.Show("You must specify where your MAME executable is located.");
            }
        }

        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            Env.SaveSettings();
            MessageBox.Show("Settings saved.");
        }

        private void closeButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (Env.Settings.IsEmpty)
            {
                if (MessageBox.Show("Mammy will close, since you haven't specified a MAME path. OK?", "Really quit?", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
                {
                    e.Cancel = true;
                }
                else
                {
                    DialogResult = false;
                }
            }
            else
            {
                DialogResult = true;
            }
        }

        private bool TryToFindSettingsAutomatically()
        {
            var possibleMamePaths = new string[] { "mame.exe", "mame64.exe" };

            foreach (string possibleMamePath in possibleMamePaths)
            {
                string mamePath = Path.Combine(Environment.CurrentDirectory, possibleMamePath);
                string romsPath = Path.Combine(Path.GetDirectoryName(mamePath), "roms");

                if (File.Exists(mamePath) && Directory.Exists(romsPath))
                {
                    Env.Settings.MamePath = mamePath;
                    Env.Settings.RomsPath = romsPath;
                    return true;
                }
            }

            return false;
        }
    }
}
